<template>
  <n-card>
    <!--用户查询-->
    <n-form inline :model="queryParams" label-placement="left">
      <n-form-item label="用户账号" path="loginCode">
        <n-input v-model:value="queryParams.loginCode" :clearable="true" />
      </n-form-item>
      <n-form-item label="用户姓名" path="userName">
        <n-input v-model:value="queryParams.userName" :clearable="true" />
      </n-form-item>
      <n-form-item label="用户部门" path="name">
        <n-tree-select
          style="width: 160px"
          v-model:value="queryParams.userOrg"
          :options="deptTree"
          label-field="name"
          key-field="id"
          children-field="children"
        />
      </n-form-item>
      <n-form-item>
        <n-button attr-type="button" @click="reloadTable">查询</n-button>
      </n-form-item>
    </n-form>

    <!--页面表格信息-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionTableRef"
      :actionColumn="actionColumn"
      v-model:checked-row-keys="checkedRowKeys"
    >
      <template #tableTitle>
        <n-button type="primary" @click="onOpenAddUser">新增用户</n-button>
      </template>
      <template #toolbar>
        <n-button type="error" @click="onDeleteUsers">批量删除</n-button>
        <n-button class="ml10" @click="onExport">导出</n-button>
      </template>
    </BasicTable>

    <Edit ref="editComponentRef" @add:success="reloadTable" @update:success="reloadTable" />
  </n-card>
</template>

<script lang="tsx" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import Edit from './edit.vue';
  import { NTag, NButton, useMessage } from 'naive-ui';
  import { getDeptTreeApi } from '@/api/system/dept';
  import {
    getUserListApi,
    deleteUserApi,
    deleteUsersApi,
    resetUserPasswordApi,
    exportUserApi,
  } from '@/api/system/user';
  import { debounce, deleteNullChildren, exportFile, structureParams } from '@/utils';

  import { activeColumnHooks } from '@/hooks/activeColumnHooks';
  import { messageHooks } from '@/hooks/baseHooks';
  const { message, IDialog } = messageHooks();

  const actionTableRef = ref();

  //修改添加组件
  const editComponentRef = ref();

  //部门树
  const deptTree = ref([]);

  /**
   * 获取部门tree数据
   */
  function onGetDeptTreeData(callback?: Function) {
    getDeptTreeApi({}).then((res) => {
      if (res && res.code === 'A00000') {
        deptTree.value = deleteNullChildren(res.data);
        if (callback) {
          callback();
        }
      }
    });
  }
  onGetDeptTreeData();

  //定义查询条件
  const queryParams = reactive({
    userName: undefined,
    loginCode: undefined,
    userOrg: undefined,
  });

  //查询表格数据
  function reloadTable() {
    actionTableRef.value.refresh(true);
  }

  //定义表格多选中项
  const checkedRowKeys = ref([]);

  //表格列配置
  const columns = [
    {
      type: 'selection',
      fixed: 'left',
    },
    {
      title: '用户账号',
      key: 'loginCode',
      align: 'center',
    },
    {
      title: '用户姓名',
      key: 'userName',
      align: 'center',
    },
    {
      title: '部门',
      key: 'userOrgName',
      align: 'center',
    },
    {
      title: '联系方式',
      key: 'mobile',
      align: 'center',
    },
    {
      title: '账号状态',
      key: 'status',
      render(row) {
        return row.status === 'ENABLE' ? (
          <NTag type="success">启用</NTag>
        ) : (
          <NTag type="error">停用</NTag>
        );
      },
    },
  ];

  //表格操作列配置
  const { actionColumn } = activeColumnHooks(handleDelete, onOpenEditUser);

  //加载表格数据方法
  const loadDataTable = async (pageation) => {
    let params = {
      pageNum: pageation.current,
      pageSize: pageation.pageSize,

      ...queryParams,
    };

    let res = await getUserListApi(structureParams(params));
    return res.data;
  };

  //点击修改按钮
  function onOpenEditUser(record: Recordable) {
    editComponentRef.value.onOpenEditUser({ ...record });
  }

  //点击删除按钮
  function handleDelete(record: Recordable) {
    IDialog.error('你确定删除当前用户?', () => {
      deleteUserApi(record).then((res) => {
        if (res && res.code === 'A00000') {
          reloadTable();
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
      });
    });
  }

  /**
   * 批量删除
   */
  function onDeleteUsers() {
    if (checkedRowKeys.value.length === 0) {
      message.warning('请选择用户');
      return;
    }

    IDialog.error('确认批量删除吗？', () => {
      deleteUsersApi(checkedRowKeys.value).then((res) => {
        if (res && res.code === 'A00000') {
          message.success(res.msg);
          reloadTable();
        }
      });
    });
  }

  /**
   * 导出
   */
  const onExport = debounce(function () {
    if (checkedRowKeys.value.length === 0) {
      message.warning('请选择用户');
      return;
    }

    exportUserApi(checkedRowKeys.value).then((res) => {
      if (res) {
        exportFile('用户.xls', [res]);
        checkedRowKeys.value = [];
      }
    });
  });

  //打开新增用户页面
  function onOpenAddUser() {
    editComponentRef.value.onOpenAddUser();
  }
</script>

<style scoped></style>
